'use strict';


const path = require('path');
const colors = require('colors');
const userHome = require('user-home');
const pathExists = require('path-exists').sync;
const { Command } = require('commander');
const pkg = require('../package.json');
const log = require('@pengsg-cli/log');
const init = require('@pengsg-cli/init');
const exec = require('@pengsg-cli/exec');
const { getSemverNpmVesion} = require('@pengsg-cli/get-npm-info');
const constants = require('./const');
let args,config;
const program = new Command();

async function core() {
    try{
        await prepare();
        registryCommander();
    }catch(e){
        log.error(e.message)
    }   
   
}

async function checkIsNeedUpdated(){
    const currentVersion = pkg.version;
    const pkgName = pkg.name;
    const latestVersion = await getSemverNpmVesion(pkgName,currentVersion);
    if(latestVersion){
        log.warn('更新提示',`当前版本: ${currentVersion}, 最新版本: ${latestVersion}, 请手动更新版本，更新指令: npm i -g ${pkgName}`)
    }
}

function checkEnv(){
    const dotEnv = require('dotenv');
    const dotEnvPath = path.resolve(userHome,'.env');
    if(pathExists(dotEnvPath)){
        dotEnv.config({
            path: dotEnvPath
        });
    }
    config = createDefaultConfig();
}

function createDefaultConfig(){
    const defaultCliConfig = {
        home: userHome
    }
    if(process.env['CLI_HOME']){
        defaultCliConfig['CLI_HOME'] = path.join(userHome,process.env.CLI_HOME)
    }else{
        defaultCliConfig['CLI_HOME'] = path.join(userHome,constants.DEFAULT_CLI_HOME)
    }
    process.env.CLI_HOME = defaultCliConfig.CLI_HOME;
    return defaultCliConfig;
}


function checkUserHome(){
    if(!userHome || !pathExists(userHome)){
        throw new Error(colors.red("当前用户使用的非用户主目录"))
    }
}

function checkRoot(){
    const rootCheck = require('root-check')
    rootCheck();
}

function checkPackageVersion(){
    log.info(pkg.version)
}



async function prepare(){
    checkPackageVersion();
    checkRoot();
    checkUserHome();
    checkEnv();
    await checkIsNeedUpdated();
}

function registryCommander() {
    program
    .name(Object.keys(pkg.bin)[0])
    .usage('[command] <option>')
    .version(pkg.version)
    .addHelpCommand()
    .option('-d --debug','开启debug模式',false)
    .option('-tp --targetPath <targetPath>','本地代码路径','')
    
    program
    .command('init [projectName]')
    .description('初始化项目')
    .option('-f --force','强制执行',false)
    .action(exec)


    program.on('option:debug',function(){
        if(program.opts().debug){
            process.env.LOG_LEVEL = 'verbose';
        }else{
            process.env.LOG_LEVEL = 'info';
        }
        log.level = process.env.LOG_LEVEL;
    })

    program.on('option:targetPath',function(){
        if(program.opts().targetPath){
            process.env.CLI_TARGET_PATH = program.opts().targetPath;
        }
        
    })

    program.parse(process.args)
}


module.exports = core;